<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use Amap\Amap;
use app\common\service\WebConfigService;
use Faker\Factory;

if (!function_exists('sys_config')) {
    /**
     * 系统配置
     * @param $key
     * @return array|mixed
     */
    function sys_config($key)
    {
        $sysConfig = (new WebConfigService())->getConfig($key);
        return $sysConfig;
    }
}

if (!function_exists('domain')) {
    /**
     * 请求地址
     * @return string
     */
    function domain(): string
    {
        return env('app_host', 'http://127.0.0.1');
    }
}

if (!function_exists('app_path')) {
    /**
     * 应用根目录
     * @param $path
     * @return string
     */
    function app_path($path = ''): string
    {
        return dirname(__DIR__) . $path;
    }
}

if (!function_exists('public_path')) {
    /**
     * 公共目录
     * @param $path
     * @return string
     */
    function public_path($path = ''): string
    {
        return dirname(__DIR__) . '/public' . $path;
    }
}

if (!function_exists('substr_cut')) {
    /**
     * 隐藏昵称
     * @param $user_name
     * @param $agolen
     * @param $afterlen
     * @return string
     */
    function substr_cut($user_name, $agolen = 1, $afterlen = 1): string
    {
        if (mb_strlen($user_name) <= 2) {
            return $user_name . '*';
        }
        $strlen = mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, $agolen, 'utf-8');
        $lastStr = mb_substr($user_name, $strlen - $afterlen, $afterlen, 'utf-8');
        return $firstStr . str_repeat("*", $strlen - $agolen - $afterlen) . $lastStr;
    }
}

if (!function_exists('create_trade_no')) {
    /**
     * 生成不重复的订单号（可以指定前缀和会员ID）
     * @param $prefix [订单前缀]
     * @param $member_id [会员ID]
     * @return string
     */
    function create_trade_no($prefix = '', $member_id = ''): string
    {
        $random = rand(1000, 9999);

        $currentDate = date('YmdHis');

        if ($member_id) {
            $trade_no = $currentDate . $random . $member_id;
        } else {
            $trade_no = $currentDate . time();
        }
        if ($prefix) {
            $trade_no = $prefix . $trade_no;
        }

        return $trade_no;
    }
}

if (!function_exists('createMobile')) {
    /**
     * 生成时间戳手机号
     * @return string
     */
    function createMobile()
    {
        $mobile = time() . rand(0, 9);
        return $mobile;
    }
}

if (!function_exists('createFullName')) {
    /**
     * 生成随机姓名
     * @return string
     */
    function createFullName()
    {
        $faker = Factory::create('zh_CN');
        return $faker->name();
    }
}

if (!function_exists('createPhoneNumber')) {
    /**
     * 生成随机手机号
     * @return string
     */
    function createPhoneNumber()
    {
        $faker = Factory::create('zh_CN');
        return $faker->phoneNumber();
    }
}

if (!function_exists('amap')) {
    /**
     * 高德地图api
     * @return Amap
     */
    function amap()
    {
        return new Amap(config('map.amap'));
    }
}

if (!function_exists('shortDateToStr')) {
    /**
     * 短日期字符串转长日期字符串
     * @param $string
     * @param $isDate
     * @return DateTime|false|string
     */
    function shortDateToStr($string, $isDate = false)
    {
        $year = substr($string, 0, 4);
        $month = substr($string, 4, 2);
        $day = substr($string, 6, 2);
        $hour = substr($string, 8, 2);
        $minute = substr($string, 10, 2);
        $second = substr($string, 12, 2);
        $time = $year . '-' . $month . '-' . $day . " " . $hour . ':' . $minute . ':' . $second;
        if ($isDate) {
            $time = date_create($time);
        }
        return $time;
    }
}

if (!function_exists('replace_url')) {
    /**
     * 替换文件地址为带域名的地址
     * @param $url
     * @return mixed|string
     */
    function replace_url($url)
    {
        if (strstr($url, 'http:') || strstr($url, 'https:') || empty($url)) {
            return $url;
        }
        $baseUrl = domain() . '/';
        $header = request()->header('user-agent');
        if (strstr($header, 'MicroMessen')) {
            $baseUrl = domain();
        }
        return $baseUrl . $url;
    }
}

if (!function_exists('replace_many_url')) {
    /**
     * 替换文件地址为带域名的地址
     * @param $urlStr
     * @return mixed|string
     */
    function replace_many_url($urlStr)
    {
        $urlArrt = explode(',', $urlStr);
        $urlList = [];
        foreach ($urlArrt as $url) {
            $urlList[] = replace_url($url);
        }
        return $urlList;
    }
}

if (!function_exists('replace_href_url')) {
    /**
     * 替换href地址返回带域名的完整下载地址
     * @param $content
     * @return array|mixed|string|string[]
     */
    function replace_href_url($content)
    {
        $preg = '/<a .*?href="(.*?)".*?>/is';
        preg_match_all($preg, $content, $array2);
        for ($i = 0; $i < count($array2[1]); $i++) //逐个输出超链接地址
        {
            if (strpos($array2[1][$i], "http") === false) {
                $content = str_replace('href="' . $array2[1][$i], 'href="' . domain() . $array2[1][$i], $content);
            }
        }

        return $content;
    }
}

if (!function_exists('replace_src_url')) {
    /**
     * 替换src地址返回带域名的完整下载地址
     * @param $content [要替换的信息]
     * @param $style [需要附加进去的附加样式]
     * @return array|mixed|string|string[]
     */
    function replace_src_url($content, $style = "")
    {
        $preg = '/<img .*?src="(.*?)".*?>/is';
        preg_match_all($preg, $content, $array2);
        if (!$array2) {
            $array2 = array();
        }
        for ($i = 0; $i < count($array2[1]); $i++) //逐个输出超链接地址
        {
            if (strpos($array2[1][$i], "http") === false) {
                $content = str_replace('src="' . $array2[1][$i], $style . ' src="' . domain() . $array2[1][$i], $content);
            }
        }

        return $content;
    }
}

if (!function_exists('date_now')) {
    /**
     * 当前时间
     * @param $format [格式]
     * @return false|string
     */
    function date_now($format = 'Y-m-d H:i:s')
    {
        return date($format, time());
    }
}

if (!function_exists('passCrypt')) {
    /**
     * 生成加密盐及加密密码
     * @param $pwd [需要加密的密码]
     * @param $len [加密盐长度]
     * @return array
     */
    function passCrypt($pwd = 'Pass_2024', $len = 8)
    {
        $pass = md5($pwd);
        $rand = mt_rand(-5, 15);
        if ($len < 6) {
            $len = 6;
        }
        if ($len > 10) {
            $len = 10;
            $rand = mt_rand(-8, 12);
        }
        $salt = substr($pass, $len + $rand, $len);
        $pwd = md5($salt . $pwd . $salt);
        return [$pwd, $salt];
    }
}

if (!function_exists('passEncryp')) {
    /**
     * 加密密码
     * @param $salt [加密盐]
     * @param $pass [需要加密的密码]
     * @return string
     */
    function passEncryp($salt, $pass = 'Pass_2024')
    {
        return md5($salt . $pass . $salt);
    }
}

if (!function_exists('passValidate')) {
    /**
     * 验证密码
     * @param $pwd [原密码]
     * @param $salt [加密盐]
     * @param $inputpwd [需要验证的密码]
     * @return bool
     */
    function passValidate($pwd, $salt, $inputpwd)
    {
        // 明文前后加随机字符，再md5加密
        if (md5($salt . $inputpwd . $salt) == $pwd) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('genRandomStr')) {
    /**
     * 生成指定长度随机字符串
     * @param $length [长度]
     * @return string
     */
    function genRandomStr($length = 12)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        $charCount = strlen($chars);

        for ($i = 0; $i < $length; $i++) {
            $randomIndex = rand(0, $charCount - 1);
            $str .= $chars[$randomIndex];
        }

        return $str;
    }
}

if (!function_exists('calculate')) {
    /**
     * 数学计算
     * @param $n1 [数字1]
     * @param $symbol [运算符]
     * @param $n2 [数字2]
     * @param $scale [保留几位小数运算]
     * @return array|int|string|string[]
     */
    function calculate($n1, $symbol, $n2, $scale = 2)
    {
        $res = "";
        if (strpos($n1, "E") > -1) {
            $n1 = 0;
        }
        if (strpos($n2, "E") > -1) {
            $n2 = 0;
        }
        switch ($symbol) {
            case "+": //加法
                if (function_exists("bcadd")) {
                    $res = bcadd($n1, $n2, $scale);
                } else {
                    $res = $n1 + $n2;
                }
                break;
            case "-": //减法
                if (function_exists("bcsub")) {
                    $res = bcsub($n1, $n2, $scale);
                } else {
                    $res = $n1 - $n2;
                }
                break;
            case "*": //乘法
                if (function_exists("bcmul")) {
                    $res = bcmul($n1, $n2, $scale);
                } else {
                    $res = $n1 * $n2;
                }
                break;
            case "/": //除法
                if ($n1 <= 0 || $n2 <= 0) {
                    return 0;
                }
                if (function_exists("bcdiv")) {
                    $res = bcdiv($n1, $n2, $scale);
                } else {
                    $res = $n1 / $n2;
                }
                break;
            case "%": //求余、取模
                if (function_exists("bcmod")) {
                    $res = bcmod($n1, $n2, $scale);
                } else {
                    $res = $n1 % $n2;
                }
                break;
            default:
                $res = "";
                break;
        }
        $res = str_ireplace(",", "", $res);
        return $res;
    }
}

if (!function_exists('calc_time_diff')) {
    /**
     * 计算时间差
     * @param $startTime
     * @param $endTime
     * @return array
     */
    function calc_time_diff($startTime, $endTime = null)
    {
        if (!$endTime) {
            $endTime = date_now();
        }
        $t = strtotime($endTime) - strtotime($startTime);//单位"秒"
        $arr = [];
        $day = intval($t / 86400);//天
        $arr['day'] = $day;
        $hour = intval((($t / 86400) - $day) * 24);//小时
        $arr['hour'] = $hour;
        $minute = intval((((($t / 86400) - $day) * 24) - $hour) * 60);//分钟
        $arr['minute'] = $minute;
        $second = intval(((((((($t / 86400) - $day) * 24) - $hour) * 60) - $minute) * 60));//秒
        $arr['second'] = $second;
        return $arr;
    }
}

if (!function_exists('curlRequest')) {
    /**
     * 通用请求
     * @param $url [请求的URL地址]
     * @param $data [请求的参数]
     * @param $ispost [是否采用POST形式]
     * @param $json [是否返回JSON格式]
     * @return bool|string
     */
    function curlRequest($url, $data = [], $ispost = true, $json = true)
    {
        $httpInfo = array();

        $header = array(
            'Accept-Encoding: gzip, deflate',//gzip解压内容
            'Accept: application/json',
            'Content-Type: application/json;charset=utf-8'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            $method = "POST";
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));//请求体
            }

            curl_setopt($ch, CURLOPT_URL, $url);//请求地址
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//请求头
        } else {
            $method = "GET";
            if ($data) {
                // 拼接请求参数
                $params = "";
                foreach ($data as $key => $item) {
                    if (!$params) {
                        $params = "?" . $key . "=" . $item;
                    } else {
                        $params .= "&" . $key . "=" . $item;
                    }
                }
                curl_setopt($ch, CURLOPT_URL, $url . $params);//请求地址
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);//请求地址
            }
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//请求方式

        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);

        // 写入日志
        $log = "";
        $log .= "----------请求开始----------\n";
        $log .= "请求地址：" . $url . "\n";
        $log .= "请求方式：" . $method . "\n";
        $log .= "请求参数：" . json_encode($data, 320) . "\n";
        $log .= "请求结果：" . $response . "\n";
        $log .= "----------请求结束----------\n";
        makelog($log);

        if ($json) {
            return json_decode($response, true);
        }
        return $response;
    }
}

if (!function_exists('makelog')) {
    /**
     * 日志生成器:生成文件
     * @param $content [日志内容]
     * @param $dir [日志路径]
     * @param $dir2 [日志文件名]
     * @return void
     */
    function makelog($content, $dir = "api", $dir2 = "")
    {
        $log_file = app()->getRuntimePath() . "log/" . $dir . "/" . date('Ym') . "/" . date('Ymd') . $dir2 . ".log";
        $path = dirname($log_file);
        !is_dir($path) && mkdir($path, 0755, true);
        $log_str = date('Y-m-d H:i:s') . "\n" . $content . "\n";
        file_put_contents($log_file, $log_str . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}